<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import {addEmployee} from '@/api/empioyees'
import { formatExcelDate } from "@/utils/index";
export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    //上传之前的回调函数,限制上传文件的大小,上传的文件必须小于1MbeforeUpload(file)
    beforeUpload(file) {
        // file.size获取到上传文件的大小单位bytes
        //1Mb=1024kb
        // 1kb= 1024bytes
        // 1bytes ----[计算机中的127个字符]1个字符的大小是1bytes一个汉字=2-6bytes
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
        // 处理成功的回调函数
        // 将excel文件中的数据读取出来转化为js数据
      this.tableData = results
      this.tableHeader = header
    //   将excel读取出来的数据进行格式化处理
    //   发送ajax请求批量添加数据(格式化之后的数据)
    const data = this.num(results)
    console.log(data);
    this.doAdd(data)
    },
    // 实现批量导入
    async doAdd(data){
        try {
            const res = await addEmployee(data)
            console.log(res);
            this.$router.back()
        } catch (error) {
            console.log(error);
        }
    },
      num(data){
            const mapInfo = {
                '入职日期': 'timeOfEntry',
                '手机号': 'mobile',
                '姓名': 'username',
                '转正日期': 'correctionTime',
                '工号': 'workNumber',
                '部门': 'departmentName',

            }


            const  num = data.map(item=>{
                const obj = Object.keys(item)
                const end= {}
                obj.forEach(ell =>{
                    const ass = mapInfo[ell]
                    if(ass==='timeOfEntry'||ass==="correctionTime"){
                      end[ass]=formatExcelDate(item[ell])
                    }else{
                      end[ass]=item[ell]
                    }
                    
                })
                return end
            })
            return num
        },


  }
}
</script>
